package com.example.bankseckill.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.example.bankseckill.mapper.SeckillOrderMapper;
import com.example.bankseckill.pojo.SeckillOrder;
import com.example.bankseckill.pojo.User;
import com.example.bankseckill.pojo.vo.RespPageBean;
import com.example.bankseckill.service.ISeckillOrderService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author liyangjing
 * @since 2022-01-26
 */
@Service
public class SeckillOrderServiceImpl extends ServiceImpl<SeckillOrderMapper, SeckillOrder> implements ISeckillOrderService {

    @Autowired
    private SeckillOrderMapper seckillOrderMapper;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 管理员查看所有秒杀订单(分页)
     * @param currentPage
     * @param size
     * @param keywords
     * @return
     */
    @Override
    public RespPageBean getSecKillOrderByPage(Integer currentPage, Integer size, String keywords) {
        //开启分页
        Page<SeckillOrder> page = new Page<>(currentPage, size);
        //将分页装入mapper层
        IPage<SeckillOrder> seckillOrderIPage = seckillOrderMapper.getSecKillOrderByPage(page,keywords);
        RespPageBean respPageBean = new RespPageBean(200,seckillOrderIPage.getTotal(), seckillOrderIPage.getRecords());
        return respPageBean;
    }

    /**
     *获取秒杀结果
     * @param user
     * @param seckillProductId
     * @return
     */
    @Override
    public Long getResult(User user, Long seckillProductId) {
        SeckillOrder seckillOrder = seckillOrderMapper.selectOne(new QueryWrapper<SeckillOrder>().eq("user_id", user.getId())
                .eq("product_id", seckillProductId));
        if(null!= seckillOrder){
            return seckillOrder.getOrderId();
        }else if(redisTemplate.hasKey("isStockEmpty:"+seckillProductId)){
            return -1L;
        }else {
            return 0L;
        }
    }
    /**
     * 获取某个秒杀订单信息
     * @param id
     * @return
     */
    @Override
    public SeckillOrder findSecOrderById(Long id) {
        return seckillOrderMapper.FindSecOrderById(id);
    }
}
